//加工入库结算（详情或者 新增)↓
<template>
  <!-- 集采汇总编辑页 -->
  <div class="e-form">
    <!-- //详情 添加页面 ↓ -->
    <div class="tabs">
      <el-tabs tab-position="left" v-model="tabsName" @tab-click="onChangeTab">
        <!-- 基本信息 -->
        <el-tab-pane
          label="基本信息"
          name="baseInfo"
          :disabled="clickTabFlag"
        ></el-tab-pane>
        <el-tab-pane
          label="加扣款明细"
          name="planDetail"
          :disabled="clickTabFlag"
        ></el-tab-pane>

        <el-tab-pane
          label="返还保证金"
          name="fhbzj"
          :disabled="clickTabFlag"
        ></el-tab-pane>

        <el-tab-pane
          label="附件信息"
          name="accessory"
          :disabled="clickTabFlag"
        ></el-tab-pane>
        <el-tab-pane
          label="审核历史"
          name="auditHistory"
          :disabled="clickTabFlag"
        ></el-tab-pane>

        <!-- <el-tab-pane
          label="审核历史"
          name="auditHistory"
          :disabled="clickTabFlag"
        ></el-tab-pane> -->
        <div>
          <!-- 基本信息 -->
          <div id="baseInfoCon" class="con">
            <div class="e-form">
              <div class="tabs">
                <div class="tabs-title" id="baseInfo">基本信息</div>
                <div style="width: 100%" class="form">
                     <el-form ref="form" :model="form" label-width="150px">
                                    <el-row>
                                        <el-col :span="12">
                                            <el-form-item label="结算编号：">
                                                <el-input v-model="formData.billNo"></el-input>
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="12">
                                            <el-form-item label="单据机构：">
                                                <el-input v-model="formData.settlementUnitName"></el-input>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row>
                                        <el-col :span="12">
                                            <el-form-item label="合同类型：">
                                                <el-select v-model="formData.contractType" placeholder="请选择">
                                                    <el-option
                                                        v-for="(item, index) in typeArr || []"
                                                        :key="index"
                                                        :label="item.name"
                                                        :value="item.id"
                                                    >
                                                    </el-option>
                                                </el-select>
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="12">
                                            <el-form-item label="合同名称：">
                                                 <el-input v-model="formData.contractName"></el-input>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row>
                                        <el-col :span="12">
                                            <el-form-item label="结算单位：">
                                                <el-input v-model="formData.settlementUnitName"></el-input>
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="12">
                                            <el-form-item label="加扣款日期：">
                                                 <el-date-picker v-model="formData.settlementDate" type="date" placeholder="选择日期" :clearable="false">
                                                </el-date-picker>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row>
                                        <el-col :span="12">
                                            <el-form-item label="加扣款金额(元)：">
                                                <el-input v-model="formData.plusDeductionAmount"></el-input>
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="12">
                                            <!-- 返回id、名字 -->
                                            <el-form-item label="返还保证金金额(元)：">
                                                <el-input v-model="formData.rmbReturnDepositAmount"></el-input>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row>
                                        <el-col :span="12">
                                            <el-form-item label="币种：">
                                                <el-input v-model="formData.currency"></el-input>
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="12">
                                            <el-form-item label="传财务共享：">
                                                <span>{{ formData.gx}}</span>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>

                                    <el-row>
                                        <el-col :span="12">
                                            <el-form-item label="本位币：">
                                               <el-input v-model="formData.baseCurName"></el-input>
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="12">
                                            <el-form-item label="状态：">
                                                <el-select v-model="formData.state" placeholder="请选择">
                                                    <el-option
                                                        v-for="(item, index) in typeArr || []"
                                                        :key="index"
                                                        :label="item.name"
                                                        :value="item.id"
                                                    >
                                                    </el-option>
                                                </el-select>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>

                                      <el-row>
                                        <el-col :span="12">
                                            <el-form-item label="加扣款金额(本位币)：">
                                               <el-input v-model="formData.baseCurPlusDeductionAmount"></el-input>
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="12">
                                            <el-form-item label="返还保证金金额：">
                                                  <el-input v-model="formData.baseCurReturnDepositAmount"></el-input>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>

                                      <el-row>
                                        <el-col :span="24">
                                            <el-form-item label="备注">
                                               <el-input type="textarea" :rows="2" laceholder="请输入内容" v-model="formData.remarks"></el-input>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>

                                </el-form>
                </div>
              </div>
            </div>
          </div>

          <!-- 汇总明细 -->
          <div id="planDetailCon" class="con">
            <div class="tabs-title" id="planDetail">加扣款明细</div>
            <el-tabs
              :class="'childTab ' + childTabClass"
              tab-position="left"
              v-model="tabsNameChild"
              @tab-click="onChangeTab"
            >
              <el-tab-pane
                label="加扣款"
                name="materialDetails"
                :disabled="clickTabFlag"
              ></el-tab-pane>
              <el-tab-pane
                label="物资明细"
                name="technicalParameter"
                :disabled="clickTabFlag"
              ></el-tab-pane>
              <div>
                <div id="planDetailCon">
                  <div class="tabs-title" id="materialDetails">
                    加扣款
                  </div>
                  <div class="e-table">
                    <div class="top">
                      <div class="left">
                        <div>
                          <el-button
                            size="small"
                            style="background: rgb(75, 178, 255); color: #fff"
                            >新增</el-button
                          >
                          <el-button
                            size="small"
                            type="danger"
                            >删除</el-button
                          >
                        </div>
                      </div>
                    </div>

                    <el-table
                      :data="tableData"
                      border
                      style="width: 100%"
                      :row-class-name="tableRowClassName"
                        @cell-click="tableDbShow"

                      :cell-class-name="cellClsNm"
                      :header-cell-style="{ textAlign: 'center' }"
                      :cell-style="{ textAlign: 'center' }"
                      @selection-change="planTableSelect"
                    >
                      <el-table-column type="selection" width="55">
                      </el-table-column>
                      <el-table-column
                        prop="annualDemandPlanBillNo"
                        label="加扣款名称"
                        min-width="300"
                      >

                      </el-table-column>
                      <el-table-column
                        prop="orgName"
                        label="加扣款类别"
                        min-width="300"
                      >
                      </el-table-column>
                      <el-table-column
                        prop="orgName"
                        label="规格"
                        min-width="300"
                      >
                      </el-table-column>
                      <el-table-column
                        prop="orgName"
                        label="单位"
                        min-width="300"
                      >
                      </el-table-column>
                      <el-table-column
                        prop="orgName"
                        label="加扣款金额"
                        min-width="300"
                      >
                      </el-table-column>
                    </el-table>

                  </div>
                </div>

                <div id="planDetailCon">
                  <div class="tabs-title" id="technicalParameter">物资汇总</div>
                  <div class="e-table">
                    <div class="top">
                      <div class="left">
                        <div>
                          <el-button
                            size="small"
                            style="background: rgb(75, 178, 255); color: #fff"
                            >选择合同清单</el-button
                          >
                          <el-button
                            size="small"
                            type="danger"
                            >删除</el-button
                          >
                        </div>
                      </div>
                    </div>
                    <el-table
                      :header-cell-style="{ textAlign: 'center' }"
                      :cell-style="{ textAlign: 'center' }"

                      :data="materialsTableData"
                      border
                      style="width: 100%; "
                      :row-class-name="tableRowClassName"
                      :cell-class-name="cellClsNm"
                      @selection-change="planTableSelect"
                       :tree-props="{
                  children: 'children',
                  hasChildren: 'hasChildren',
                }"
                  default-expand-all
                       row-key="uuid"
                    >
                    <el-table-column
                        label="操作"
                        fixed
                        width="100px"
                        align="left"
                      >
                        <template slot-scope="{ row ,$index}">
                          <i
                            class="el-icon-delete"
                            style="cursor: pointer; font-size: 20px"
                            :class="{
                              'icon-delete-active-color':
                                MouseEnterId == row.dtlId,
                            }"
                            @click="deleteEle(row)"
                             v-if="$index > 0"
                          ></i>
                        </template>
                      </el-table-column>
                      <el-table-column prop="materialClassName" label="物资类别" width="150">
                      </el-table-column>
                      <el-table-column
                        prop="materialName"
                        label="物资名称"
                        min-width="200"
                      >
                      <template slot-scope="scope">
                          <span
                            @click="showA(scope.row)"
                            style="color: blue; cursor: pointer"
                          >
                            {{ scope.row.materialName }}
                          </span>
                        </template>
                      </el-table-column>
                      <el-table-column prop="spec" label="规格型号" width="100">
                      </el-table-column>
                      <el-table-column prop="unit" label="计量单位" width="100">
                      </el-table-column>
                      <el-table-column prop="texture" label="材质" width="100">
                      </el-table-column>
                      <el-table-column prop="planQuantity" label="计划数量" width="100">
                      </el-table-column>
                      <el-table-column prop="planPrice" label="单价（元）" width="100">
                      </el-table-column>
                      <el-table-column prop="amount" label="金额（元）" width="100">
                      </el-table-column>

                      <el-table-column prop="purchaseType" label="采购方式" width="100">
                      </el-table-column>
                       <el-table-column
                        prop="d"
                        label="集中采购单位"
                        min-width="150"
                      >
                      </el-table-column>
                    </el-table>
                  </div>
                </div>
              </div>
            </el-tabs>
          </div>

          <div id="fhbzjCon" class="con">
            <div class="tabs-title" id="fhbzj">返还保证金</div>
            <div class="e-table" style="min-height: auto">
                <div class="top">
                      <div class="left">
                        <div>
                          <el-button
                            size="small"
                            style="background: rgb(75, 178, 255); color: #fff"
                            @click="xzbzj"
                            >选择保证金</el-button
                          >
                          <el-button
                            size="small"
                            type="danger"
                            >删除</el-button
                          >
                        </div>
                      </div>
                    </div>
                            <el-table
                                :data="tableData"
                                border
                                style="width: 100%"
                                @cell-mouse-enter="cellMouseEnter"
                                @cell-mouse-leave="cellMouseLeave"
                                :cell-class-name="cellClsNm"
                            >
                                <el-table-column prop="a1" label="保证金名称" > </el-table-column>
                                <el-table-column prop="a" label="暂扣保证金(元)" width="250"> </el-table-column>
                                <el-table-column prop="b" label="返还保证金(元)" width="250"> </el-table-column>
                                <el-table-column prop="c" label="截止上期末已返还保证金(元)" width="250"> </el-table-column>
                                <el-table-column prop="d" label="截止本期末已返还保证金(元)" width="250"> </el-table-column>
                                <el-table-column prop="d" label="截止本期末未返还保证金(元)" width="250"> </el-table-column>
                            </el-table>
            </div>
                            <!-- <ComPagination /> -->
          </div>

          <!-- 附件信息 -->
          <div id="accessoryCon" class="con">
            <div class="tabs-title" id="accessory">附件信息</div>
            <attach-comp
              :relationId="attachId"
              bucketName="turnover"
            />
          </div>
          <!-- 审核历史 -->
          <div id="auditHistoryCon" class="con">
            <div class="tabs-title" id="auditHistory">审核历史</div>
            <div class="e-table">
            <div class="e-table">
                            <ComAuditHistoryIndex/>
                        </div>
            </div>
          </div>
        </div>
      </el-tabs>
    </div>
    <div id="seat" :style="{ height: seatHeight + 'px' }"></div>
           <div class="buttons">
            <span class="tip"><span style="color: red; margin-right: 0">*</span>为必填项</span>
            <el-button
            type="primary"
            class="btn-blue"
            @click="submitCommit"
            size="small"
            >保存并提交</el-button
            >
            <el-button
                type="primary"
                class="btn-blue"
                @click="submit"
                size="small"
                >保存</el-button
            >
            <el-button
                type="primary"
                class="btn-delete"
                @click="nullify"
                v-if="statusLable(basicFormData.state) === '审核中'"
                size="small"
                >作废</el-button
            >
            <!-- <ComExaButtons :auditState="auditState" @exas="exas" v-if="statusLable(formData.planConfiguration.state) !== '已作废'"/> -->
            <el-button size="small" @click="handleClose">取消</el-button>
        </div>

    <span style="display: none">{{ localPopConfirm }}</span>
  </div>
</template>

<script>
import '@/utils/jquery.scrollTo.min'
import { mapMutations, mapState } from 'vuex'
import { showPromptPop, showSuccessPop, getUuid } from '@/utils/common'
import AttachComp from '@/components/common/attachIndex'
import planRequest from '@/api/turnover/plan.js'
import { selectDataClient, openAppClient } from '@/utils/common'

import auditRequest from '@/api/turnover/audit.js'
import ComAuditHistoryIndex from '@/pages/revolveMaterialManage/components/auditHistory/auditHistoryIndex'
// import historyUpdateTable from '@/components/common/historyUpdateTable'

export default {
    components: {
        AttachComp,
        ComAuditHistoryIndex,
        // historyUpdateTable
    },
    data () {
        return {
            //我的数据:↓
            formData: {
                billNo: '',
                settlementUnitName: '', //单据机构name
                contractType: '', //合同类型
                contractName: '', //合同名称
                // settlementUnitName: '', //结算单位名称
                settlementUnitId: '', //结算单位ID
                settlementDate: '', //加扣款日期
                plusDeductionAmount: 0, //加扣款金额
                rmbReturnDepositAmount: '', //返还保证金金额(人民币)
                currency: '', //币种
                gx: '', //传财务共享 随便写的 需要改
                baseCurName: '', //本位币name
                baseCurId: '', //本位币id
                state: '', //状态
                baseCurPlusDeductionAmount: 0, //加扣款金额(本位币)
                baseCurReturnDepositAmount: 0, //返回保证金金额
                remarks: '' //备注
            },
            typeArr: [
                { name: '草稿', id: 0 },
                { name: '审核中', id: 1 },
                { name: '共享审核中', id: 9 },
                { name: '已审核', id: 2 },
                { name: '已关闭', id: -1 },
                { name: '已作废', id: 5 },
            ],
            viewList: true,
            paginationInfo: {
                total: 1,
                pageSize: 10,
                currentPage: 0
            },
            query: {
                beginPlanDate: '',
                endPlanDate: '',
                keyword: '',
                limit: 0,
                orgId: '',
                page: 1,
                settlementUnitId: '',
                states: []
            }, //搜索
            searchKey: '', //右上角搜索关键字
            tableData: [], //表格
            //我的数据:↑

            auditState: {},
            auditParams: {
                billId: this.$route.query.billid,
                billType: 6087,
                freeNextUnitIndex: 0,
                freeNextUser: '',
                isPass: true,
                isShareInAudit: true,
                opinion: ''
            },
            tabsName: 'baseInfo',
            userName: '',
            clickId: 'baseInfo',
            tabsNameChild: '',
            childTabClass: '',
            form: {
                name: '',
                region: '',
                date1: '',
                date2: '',
                delivery: false,
                type: [],
                resource: '',
                desc: '',
            },

            OrgtableData: [], //申报机构数据
            OrgSonTableData: [], //申报机构子列表
            materialsTableData: [], //物资汇总数据
            auditHistoryList: [], //审核历史
            planSelect: [], //申报机构表格明细选择项
            value: '',
            textarea: '',
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            MouseEnterId: 0,
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            //基本信息表单数据
            basicFormData: {
                'amount': null,
                'billId': '',
                'billNo': '',
                'founderId': '',
                'founderName': '',
                'gmtCreate': '',
                'gmtModified': '',
                'nullifyCreated': '',
                'nullifyCreator': '',
                'nullifyCreatorId': '',
                'nullifyDescription': '',
                'nullifyReason': '',
                'operator': '',
                'operatorId': '',
                'orgId': '',
                'orgName': '',
                'remarks': '',
                'sourceBillId': '',
                'sourceBillNo': '',
                'sourceType': null,
                'state': '',
                'summaryDate': '',
                'workId': ''
            },
            objFlag: {
                flag5: false,
            },
            orgId: '', //机构id
            orgName: '', //机构名称
            billId: '',
            isSkip: false, //是否跳转
            show: true, //申报机构子列表
            dtlIds: '', //
            //验证
            rules: {
                summaryDate: [
                    { required: true, message: '请输入汇总日期', trigger: 'blur' },
                ],
                currencyId: [
                    { required: true, message: '请选择币种', trigger: 'chenge' },
                ],
            },
            materialsNameData: [], //机构汇总表
            createHistoryData: [], //明细修改历史列表
            errorMsg: [],
            isErrorMsg: true, //是否提醒错误信息

        }
    },
    created () {
        // let data = JSON.parse(localStorage.getItem('vuex'))
        // this.orgId = data.userInfo.orgInfo.orgId
        // this.orgName = data.userInfo.orgInfo.orgName
        // this.userId = localStorage.getItem('userId')
        // this.basicFormData.operator = localStorage.getItem('userName')
        // this.billId = this.$route.query.billid

        // this.initData()
    },
    methods: {
        ...mapMutations(['setPopConfirm', 'setSelectedInfo', 'setHistoryTableData']),

        initData () {
            this.getCurrentUnitInfo()
            this.getTurnoverCentralizedPurchaseSummaryGetAgencyListByBillId()
            this.getBasicData()
            this.getTurnoverCentralizedPurchaseSummaryGetSummarySetting() //回去物资汇总明细
        },
        //获取按钮状态
        getCurrentUnitInfo () {
            auditRequest.getCurrentUnitInfo(this.auditParams).then(res => {
                this.auditState = res
            })
        },
        //根据周材集采汇总id查询申报机构
        getTurnoverCentralizedPurchaseSummaryGetAgencyListByBillId () {
            planRequest.turnoverCentralizedPurchaseSummaryGetAgencyListByBillId(this.billId).then(res=>{
                this.OrgtableData = res
                // this.rollUp(res)
            })
        },

        //根据周材集采汇总id查询申报机构
        getTurnoverCentralizedPurchaseSummaryGetSummarySetting () {
            planRequest.turnoverCentralizedPurchaseSummaryGetSummarySetting(this.billId).then(res=>{
                console.log(res, '当前打印')
                // this.OrgtableData = res
                this.notSetData = JSON.parse(JSON.stringify(res)) //没去重之前的数据
                //去重
                let children = []
                res.forEach(item=>{
                    item.children.forEach(a=>{
                        children.push(a)
                    })
                })
                var result = []
                var obj = {}
                for (var i = 0; i < children.length; i++) {
                    if ( children[i].materialId in obj) {
                        // 相同时肯定不push
                        if (obj[children[i].materialId] !== children[i].texture) {
                            // 不相同时，判断是否是 '' 和 null，如果是，则表示重复
                            if (!(!obj[children[i].materialId] && !children[i].texture)) {
                                // 当都不是 '' 和 null 时，才表示不重复，此时才push
                                result.push(children[i])
                            }
                        }
                    } else {
                        obj[children[i].materialId] = children[i].texture
                        result.push(children[i])
                    }
                    // obj[children[i].amount] = 1

                }
                res.forEach(item=>{
                    item.uuid = getUuid()

                    item.materialClassName = item.topClassName
                    item.children = result
                    item.children.forEach(v=>{
                        v.uuid = getUuid()
                        v.parentId = item.uuid
                    })
                })
                console.log(result, 'datadata')
                this.materialsTableData = res
            })
        },

        //向上汇总
        rollUp (res) {
            res.forEach(item=>{ //拿到 数据 汇总计划金额
                this.basicFormData.amount += item.totalAmount
            })
        },
        //点击图标的时候 获取历史记录
        clickIcon (dtlId, column) {
            this.setHistoryTableData([])
            alert(dtlId)
            planRequest
                .turnoverAnnualDemandPlanGetHistoryList(
                    dtlId,
                    column,
                    this.auditParams.billType
                )
                .then(res => {
                    this.historyTableData = res
                    this.setHistoryTableData(res)
                })
                .catch(e => {
                    alert(e.message)
                })
        },
        // 编辑的时候造历史修改数据结构
        createHistory (row, e) {
            if (row.dtlId) {
                this.createHistoryData.push({
                    historyId: '',
                    modifedName: '',
                    modifiedDate: '',
                    modifiedId: '',
                    opinion: '',
                    sourceId: row.dtlId,
                    sourceValue: 0,
                    updateColumn: e, //修改字段
                    updatedValue: row[e] //修改后的值
                })
            }
        },
        /**
         * 下边几个按钮
         */

        //保存按钮
        submit () {
            this.$refs['basicFormData'].validate(valid => {
                if (valid) {
                    const data = JSON.parse(JSON.stringify(this.OrgtableData))

                    // 明细非空验证
                    this.verifyTable()
                    if (this.isErrorMsg) {
                        return
                    }
                    return new Promise((resolve, reject)=>{

                        planRequest.turnoverCentralizedPurchaseSummaryUpdateDtlList(data).then(res=>{
                            resolve(res)
                            showSuccessPop('保存明细成功！', this.initData)
                        }).catch(err=>{
                            reject(err)
                        })
                        if(this.isCollect) { //初次进入页面 点击了申报单位之后的回调s
                            const resource = []
                            data.forEach(item=>{
                                if(item.dtls) {
                                    item.dtls.forEach(v=>{
                                        v.children.forEach(n=>{
                                            n.billId = this.billId
                                        })
                                        resource.push(v)
                                    })
                                }

                            })
                            planRequest.turnoverCentralizedPurchaseSummarySaveSummarySetting(resource).then(res=>{
                                resolve(res)
                                showSuccessPop('保存物资汇总成功！', this.initData)
                            }).catch(err=>{
                                reject(err)
                            })
                        }

                        //修改基础信息
                        planRequest.turnoverCentralizedPurchaseSummaryUpdate(this.basicFormData).then(res => {
                            resolve(res)
                            showSuccessPop('保存基础成功！', this.initData)
                        }).catch(err=>{
                            reject(err)
                        })
                    })

                }
            })
        },

        // 保存并提交
        submitCommit () {
            const data = JSON.parse(JSON.stringify(this.OrgtableData))
            if(!data.length) {
                this.clientPop('err', '请选择申报机构!')
                return
            }
            this.verifyTable()
            if (this.isErrorMsg) {
                return
            }
            let promise1 = planRequest.turnoverCentralizedPurchaseSummaryUpdate(
                this.basicFormData
            )
            const promise2 =  planRequest.turnoverCentralizedPurchaseSummaryUpdateDtlList(data).then()
            Promise.all([promise1, promise2]).then(() => {
                auditRequest.commit(this.auditParams).then(()=>{

                    this.clientPop('suc', '保存并提交成功', this.handleClose)
                })
            })
        },
        //计划明细非空验证
        verifyTable () {

            this.errorMsg = []
            if(this.OrgtableData.length > 0) {
                this.OrgtableData.forEach((n, index)=>{
                    if(n.dtls) {
                        n.dtls.forEach(v=>{
                            v.children.forEach(item=>{
                                if(item.changeType !== -1) {
                                    if (item.approvalQuantity == '' || item.approvalQuantity == null) {
                                        let str = `请填写第 ${index + 1} 行的核准数量`
                                        this.errorMsg.push(str)
                                    }
                                    if (item.approvalPrice == '' || item.approvalPrice == null) {
                                        let str = `请填写第 ${index + 1} 行的核准单价`
                                        this.errorMsg.push(str)
                                    }

                                }
                            })
                        })
                    }

                })
            }

            if(this.errorMsg.length > 0) {
                this.isErrorMsg = true

            }else{
                this.isErrorMsg = false

            }

        },
        nullify () {
            //作废
            this.setAuditParams(this.nullifyParams)
            // 客户端弹窗弹出本地页面
            openAppClient('/nullifyDialog', '单据作废原因', () => {
                const auditParams = JSON.parse(
                    localStorage.vuex
                ).auditParams
                auditRequest.nullify(auditParams).then(() => {
                    this.clientPop('suc', '作废成功')
                    this.getCurrentUnitInfo()
                })
            })
        },
        //把子列表的数据合并到this.OrgtableData的children
        DoMaterialsTableData () {
            this.OrgtableData.forEach(item=>{
                item.changeType = 1
                item.billId = this.billId

            })
        },

        //点击选择 选择申报单位 获取申报机构
        selectUnit () {
            planRequest.turnoverCentralizedPurchaseSummaryGetAgencyListByOrgId(['1505122036192309249'])
                .then(res => {
                    this.OrgtableData = res
                    this.DoMaterialsTableData() //给数据造billid 和 chengetype
                    this.isCollect = true
                })
        },
        //点击申报单位列表点击编号显示对应子列表
        tableDbShow (row, column) {
            row.dtls = []
            if(column.label === '年度需用计划编号') {
                if(row.changeType == 1) {
                    planRequest.turnoverCentralizedPurchaseSummaryGetAllMaterial(row.annualDemandPlanBillId).then(res=>{
                        this.OrgSonTableData = res
                        this.OrgSonTableData.forEach(item=>{
                            item.changeType = 1
                            item.uuid =  getUuid()
                            item.materialClassName = item.topClassName

                            item.children.forEach(v=>{
                                v.changeType = 1
                                v.parentId = item.uuid
                                v.uuid =  getUuid()
                            })
                            row.dtls.push(item)
                        })
                    })
                }else {
                    planRequest.turnoverCentralizedPurchaseSummaryGetMaterial(row.dtlId).then(res=>{
                        this.OrgSonTableData = res
                        this.OrgSonTableData.forEach(item=>{
                            item.uuid =  getUuid()
                            item.materialClassName = item.topClassName
                            row.dtls.push(item)
                            item.children.forEach(v=>{
                                v.changeType = 2
                                v.parentId = item.uuid
                                v.uuid =  getUuid()
                            })
                        })
                    })
                }

            }

        },
        // 点击子表的选择明细
        selectDetails () {
            console.log('选择明细')
        },
        //点击集中采购单位 选择单位

        clickPurchasingUnit (row) {
            selectDataClient()
            // 弹窗选择数据
            selectDataClient({
                SelectServiceToken: '/hr/org/getChildrenOrg', // 客户端对应方法名
                IsSingleMode: true, // 是否单选 true 单选 false 多选
                SelectedIDs: [], // 已选中id
                Title: '选择全集团组织机构数据', // 标题
                InitParamsStr: JSON.stringify({ orgId: this.basicFormData.orgId }), //参数

            }).then(val => {
                const orgData = val[0] //获取客户端返回的数据
                row.purchasingUnitId = orgData.orgId
                row.purchasingUnitName = orgData.orgName
                row.changeType === 1 ? this.count_(row, 1) : this.count_(row, 2) //判断当前的状态是新增还是修改
                // 保存用户选择返回数据到store
                this.setSelectedInfo(val)
                // 客户端弹窗预览结果
                // 参数依次为: 打开页面地址、标题、回调函数
                // openAppClient('/showSelectedData', '选择结果', function () {
                //     alert('关闭后回调')

                // })
            })
        },
        //点击物资汇总的物资名称，汇总物资下的所有机构
        showA (row) {
            console.log(row, 'row')
            console.log(this.notSetData, 'this.notSetData')
            this.materialsNameData = []
            this.notSetData.forEach(item=>{
                item.children.forEach(b=>{
                    if( row.materialId === b.materialId) {
                        // const obj = {
                        //     orgName: item.orgName,
                        //     materialName: b.materialName,
                        //     spec: b.spec,
                        //     unit: b.unit,
                        //     texture: b.texture,
                        //     planQuantity: b.planQuantity,
                        //     marketPrice: '',
                        //     amount: b.amount
                        // }
                        // this.materialsNameData = []
                        this.materialsNameData.push(b)
                    }
                })
            })

        },
        //申报机构汇总-删除 申报机构汇总表格明细
        deleteMaterials () {
            if (this.planSelect.length > 0) {
                this.OrgtableData.forEach(v=>{
                    this.planSelect.forEach(item=>{
                        if(item.dtlId && item.dtlId === v.dtlId) {
                            v.changeType = -1
                        }
                    })

                })
            }
            if (this.planSelect.length > 0) {
                this.planSelect.forEach(item => {
                    if (item.dtlId) {
                        const newArr = []
                        newArr.push(item)
                        newArr.forEach(item => {
                            this.$set(item, 'changeType', -1)
                        })

                        // this.$refs.multipleTable.clearSelection()
                    } else {
                        const localArr = []
                        localArr.push(item)
                        for (
                            let i = this.OrgtableData.length;
                            i > 0;
                            i--
                        ) {
                            for (let j = 0; j < localArr.length; j++) {
                                if (
                                    this.OrgtableData[i - 1] ===
                                    localArr[j]
                                ) {
                                    this.OrgtableData.splice(i - 1, 1)
                                }
                            }
                        }
                        // this.$refs.multipleTable.clearSelection()
                    }
                })
            }
            console.log(this.OrgtableData)

        },

        //监听明细 机构汇总表格 数据input事件 判断用户是否修改  ，计算金额
        countInput (row) {
            row.changeType === 1 ? this.count_(row, 1) : this.count_(row, 2)
            console.log(this.materialsTableData, '物资汇总')
        },
        // 汇总逻辑
        count_ (row, num) {
            row.changeType = num
            this.basicFormData.amount = null

            row.approvalAmount =  row.approvalQuantity * row.approvalPrice
            this.OrgtableData.forEach(item =>{
                console.log(item, '逻辑汇总')
                item.changeType = num
                this.basicFormData.amount += item.totalAmount = row.approvalAmount  //把汇总的金额给父级 方便汇总计算
                if(item.children) {
                    item.children.forEach(i=>{
                        i.changeType = num
                    })
                }
            })
        },
        //申报机构汇总-明细子列表删除按钮
        deleteEle (row) {

            row.changeType = -1
            this.OrgtableData.forEach(item =>{
                item.changeType = 2
                if(item.dtls) {
                    item.dtls.forEach(v=>{
                        if(v.children) {
                            const data =  v.children.find(i=>{
                                return i.dtlId === row.dtlId
                            })
                            data.changeType = -1

                        }
                    })
                }
            })

        },
        //获取集采汇总id获取基本信息
        getBasicData () {
            planRequest.turnoverCentralizedPurchaseSummaryFindById(this.billId)
                .then(res => {
                    this.basicFormData = res
                })
        },
        //删除提示框
        ctDelete () {
            showPromptPop('确定要删除吗？删除的数据可以在【回收站】还原或彻底删除。')
        },
        //根据集采汇总id删除单据
        delData () {
            planRequest.turnoverCentralizedPurchaseSummaryDelete(this.billId)
                .then(res => {
                    if (res.code == 200) {
                        showSuccessPop('删除成功！')
                        this.isSkip = true
                    }
                    this.$router.push('./revolveCollectList')
                })
        },
        handleFullScreen () {
            this.fullscreen = !this.fullscreen
        },
        //查询附件信息
        getAttach () {
            this.objFlag.flag5 = true
        },
        //申报机构删除逻辑
        tableRowClassName ({ row }) {
            if (row.changeType === -1) {
                return 'warning-row'
            }
            return ''
        },
        //获取用户在 汇总明细-申报机构汇总 表格的已选择项
        planTableSelect (selection) {
            this.planSelect = selection
        },
        //取消
        handleClose () {
            // this.dialogVisible = false
            this.$router.replace('/supplierAddpaymentlist')
        },
        onChangeTab (e) {
            console.log('clickTabFlag: ', this.clickTabFlag)
            $.scrollTo(`#${e.name}`, 500)
            this.clickId = e.name //记录每次点击的id
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
        },
        // 获取最后一个内容区域的高度，计算底部空白
        getLastConHeight () {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                if (document.getElementById('evaluateCon')) {
                    const lastConHeight =
            document.getElementById('evaluateCon').offsetHeight
                    console.log('lastConHeight: ', lastConHeight)
                    this.lastConHeight = lastConHeight
                    console.log('this.lastConHeight', this.lastConHeight)
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },
        cellClsNm ({ column }) {
            if (column.label === '') {
                return 'fixed-left'
            }
        },

        //本人方法 ↓
        xzbzj () {
            console.log('返还保证金弹框，选择合同物资明细')
        },

    },
    computed: {
        ...mapState({
            options: state => state.contract.ctClassify,
            popConfirm: 'popConfirm',
            popStatus: 'popStatus',
            userInfo: state => state.userInfo,
            currencyForm: state => state.equip.equipData.currencyForm//币种
        }),
        localPopConfirm () {
            if (this.popConfirm) {
                switch (this.popStatus) {
                case 'prompt':
                    this.delData()
                    break
                case 'success':
                    if (this.isSkip) this.handleClose()
                    break
                }
                this.setPopConfirm(false)
            }
            return this.popConfirm
        },
        judgeRoute () {
            if (this.$route.path.includes('Add')) {
                return false
            }
            return true
        },
        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 72 - this.lastConHeight
        },
        attachId () {
            return this.billId
        },
        statusLable () {
            return param => {
                const state = this.$store.state.equip.equipData.state
                const obj = state.find(x => x.value == param)

                if (obj !== undefined) {
                    return obj.label
                }
            }
        },
    },

    mounted () {
    // 获取最后一个内容区域的高度，计算底部空白
        this.getLastConHeight()

        // 保存所有tabName
        const arr = [
            'baseInfo',
            'fhbzj',
            ['planDetail', 'materialDetails', 'technicalParameter'],
            'accessory',
            'auditHistory',
        ]
        let $idsTop = []
        window.addEventListener('scroll', () => {
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            //当点击的tab有子tab时做滚动逻辑
            if (this.clickTabFlag && arr.find(x => x === this.clickId)) {
                this.childTabClass = '' //无子tab时清空tab的类名
                return
            }

            if (!$idsTop[$idsTop.length - 1]) {
                $idsTop = arr.map(item => {
                    let itemTop
                    let arr
                    if (item instanceof Array) {
                        const prevHeight = document.getElementById(item[0]).offsetHeight //因这里一个选项有两个表格，需获取前一个表格的高度进行计算
                        arr = item.map((x, i) => {
                            if (i === 0) {
                                return document.getElementById(x).offsetTop
                            } else {
                                return (
                                    document.getElementById(x).offsetTop +
                  prevHeight +
                  document.getElementById(item[0]).offsetTop
                                )
                            }
                        })
                        return arr
                    } else {
                        itemTop = document.getElementById(item).offsetTop
                        return itemTop
                    }
                })
            }
            const scrollTop =
        document.documentElement.scrollTop || document.body.scrollTop
            // 倒序查找
            let curLocal = 0
            let curLocalChild = 1
            for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                if ($idsTop[i] instanceof Array) {
                    let item = $idsTop[i]
                    for (let lenth = item.length, j = lenth - 1; j >= 1; j--) {
                        let itemChild = $idsTop[i][j]
                        if (scrollTop + 1 >= itemChild) {
                            curLocalChild = j
                            break
                        }
                    }
                    if (scrollTop + 1 >= item[0]) {
                        curLocal = i
                        break
                    }
                } else {
                    let item = $idsTop[i]
                    if (scrollTop + 1 >= item) {
                        curLocal = i
                        break
                    }
                }
            }
            // 设置对应tabName
            if (arr[curLocal] instanceof Array) {
                this.tabsName = arr[curLocal][0]
                this.tabsNameChild = arr[curLocal][curLocalChild]
            } else {
                this.tabsName = arr[curLocal]
            }
            //动态改变二级选项卡类名
            arr.forEach((item, index) => {
                if (item instanceof Array) {
                    let tabNavHeight = document.querySelector('.childTab .el-tabs__nav')
                        ? document.querySelector('.childTab .el-tabs__nav').offsetHeight
                        : 0
                    if (scrollTop + 1 >= $idsTop[index + 1] - tabNavHeight) {
                        this.childTabClass = 'childTab2'
                    } else if (scrollTop <= $idsTop[index][1]) {
                        this.childTabClass = ''
                    } else {
                        this.childTabClass = 'childTab1'
                    }
                }
            })
        })

        this.screenWidth = document.documentElement.clientWidth
        this.screenHeight = document.documentElement.clientHeight
        window.addEventListener('resize', () => {
            this.screenWidth = document.documentElement.clientWidth
            this.screenHeight = document.documentElement.clientHeight
            $idsTop = arr.map(item => {
                let itemTop
                let arr
                if (item instanceof Array) {
                    const prevHeight = document.getElementById(item[0]).offsetHeight //因这里一个选项有两个表格，需获取前一个表格的高度进行计算
                    arr = item.map((x, i) => {
                        if (i === 0) {
                            return document.getElementById(x).offsetTop
                        } else {
                            return (
                                document.getElementById(x).offsetTop +
                prevHeight +
                document.getElementById(item[0]).offsetTop
                            )
                        }
                    })
                    return arr
                } else {
                    itemTop = document.getElementById(item).offsetTop
                    return itemTop
                }
            })
        })
    },
}
</script>

<style lang="scss" scoped>
.buttons {
  left: 0;
}
.e-form {
  margin-bottom: 80px;
  padding: 0 20px;
  .tabs-title::before {
    content: "";
    height: 22px;
    width: 8px;
    border-radius: 40px;
    background-color: #2e61d7;
    display: block;
    position: absolute;
    left: 20px;
    margin-right: 20px;
  }
}

.e-table {
  background: #fff;
}
::v-deep.el-table .warning-row {
  display: none;
}
// ::v-deep.el-table__body-wrapper::-webkit-scrollbar{
//      width: 6px !important; // 横向滚动条
//     height: 10px !important// 纵向滚动条
// }

::v-deep .el-table__body-wrapper::-webkit-scrollbar {
  width: 6px; // 横向滚动条
  height: 10px; // 纵向滚动条
}
// 滚动条的滑块
::v-deep .el-table__body-wrapper::-webkit-scrollbar-thumb {
  background-color: #ddd;
  border-radius: 5px;
}

.el-tab-pane {
  margin-left: -10px;
}
.childTab {
  ::v-deep .el-tabs__header {
    position: absolute !important;
  }
  ::v-deep .el-tabs__content {
    padding: 0 0 0 20px !important;
  }
}
.childTab1 {
  ::v-deep .el-tabs__header {
    position: absolute !important;
    .el-tabs__nav-scroll {
      position: relative;
      .el-tabs__nav {
        position: fixed;
        top: 0;
        width: 190px;
      }
    }
  }
}
.childTab2 {
  ::v-deep .el-tabs__header {
    position: absolute !important;
    .el-tabs__nav-scroll {
      position: relative;
      .el-tabs__nav {
        position: absolute;
        bottom: 0;
        width: 100%;
      }
    }
  }
}
</style>

